package org.csu.demo.controller;


import org.csu.demo.common.CommonResponse;
import org.csu.demo.domain.*;
import org.csu.demo.service.CatalogService;
import org.csu.demo.service.InventoryService;
import org.csu.demo.service.RecordService;
import org.csu.demo.service.impl.CartServiceImpl;
import org.csu.demo.service.impl.OrderServiceImpl;
import org.csu.demo.service.impl.RecordServiceImpl;
import org.csu.demo.service.impl.UserServiceImpl;
import org.csu.demo.util.JwtUtil;
import org.csu.demo.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@RestController
@Validated
public class MypetstoreController {
    @Autowired
    private CatalogService catalogService;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private CartServiceImpl cartService;
    @Autowired
    private OrderServiceImpl orderService;
    @Autowired
    private RecordService recordService;
    @Autowired
    private InventoryService inventoryService;


    //获取全部categories
    @GetMapping("/categories")
    public CommonResponse<List<Category>> getCategories(){
        CommonResponse<List<Category>> result = catalogService.findAllCategories();
        return result;
    }

    //根据ID获取category
    @GetMapping("/categories/{id}")
    public CommonResponse<Category> getCategory(@PathVariable("id") String categoryId){
        CommonResponse<Category> result = catalogService.findCategoryById(categoryId);
        return result;
    }

    //根据categoryid获取products
    @GetMapping("/categories/{id}/products")
    public CommonResponse<List<Product>> getProductsByCategoryId(@PathVariable("id") String categoryId){
        CommonResponse<List<Product>> result = catalogService.findProductsByCategory(categoryId);
        return result;
    }

    //获取全部product
    @GetMapping("/products")
    public CommonResponse<List<Product>> getProducts(){
        CommonResponse<List<Product>> result = catalogService.findAllProducts();
        return result;
    }

    //根据productid获取单个product
    @GetMapping("/products/{id}")
    public CommonResponse<Product> getProduct(@PathVariable("id") String productId){
        CommonResponse<Product> result = catalogService.findProductById(productId);
        return result;
    }

    //根据关键词获取匹配的productList
    @GetMapping("/productList/{key}")
    public CommonResponse<List<Product>> searchProductList(@PathVariable("key") String key){
        return catalogService.searchProducts(key);
    }

    //获取全部items
    @GetMapping("/items")
    public CommonResponse<List<Item>> getItems(){
        CommonResponse<List<Item>> result = catalogService.findAllItems();
        return result;
    }

    //根据productid获取对应的items
    @GetMapping("/products/{id}/items")
    public CommonResponse<List<Item>> getItemsByProductId(@PathVariable("id") String productId){
        CommonResponse<List<Item>> result = catalogService.findItemsByProductId(productId);
        return result;
    }

    //根据itemid获取对应的item
    @GetMapping("/items/{id}")
    public CommonResponse<Item> getItemById(@RequestHeader("Authorization") String token,@PathVariable("id") String itemId){
        CommonResponse<Item> result = catalogService.findItemById(itemId);
        try {
            Map<String,Object> claims = JwtUtil.parseToken(token);
            String username = claims.get("username").toString();
            if(username != null){
                //记录浏览商品
                recordService.recordViewItem(username,itemId,result.getData().getProductId());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    //user

    //用户注册
    @PostMapping("users")
    public CommonResponse<User> register(@RequestBody User user){
        CommonResponse<User> result = userService.register(user);
        return result;
    }

    //获取当前登录用户的信息
    //新增了第三方的判断
    @GetMapping("/users")
    public CommonResponse<User> getUser(){
        String username = ThreadLocalUtil.getUsername();
        //如果是第三方登录
        if(userService.isUsernameExist(username).getMessage().equals("Not Exist")){
            //设置模板用户的名字为demo
            CommonResponse<User> result = userService.getUserByUsername("demo");
            User user = result.getData();
            Sign sign = user.getSign();
            Account account = user.getAccount();
            Profile profile = user.getProfile();
            sign.setUsername(username);
            account.setUsername(username);
            profile.setUsername(username);
            sign.setPassword(null);
            user.setSign(sign);
            user.setAccount(account);
            user.setProfile(profile);
            return CommonResponse.createForSuccess(user);
        }else{
            CommonResponse<User> result = userService.getUserByUsername(username);
            return result;
        }

    }

    //修改用户的信息
    @PutMapping("/users")
    public CommonResponse<User> updateUser(@RequestBody User user){
        String username = ThreadLocalUtil.getUsername();
        return userService.updateUser(user,username);
    }

    @GetMapping("/users/{id}")
    public CommonResponse<User> isUsernameExist(@PathVariable("id") String username){
        CommonResponse<User> result = userService.isUsernameExist(username);
        return result;
    }
    //用户登出
    //只用前端将拥有的JWT令牌删除即可
    /*@DeleteMapping("/tokens/{id}")
    public CommonResponse<User> signOut(@PathVariable("id") String username,
                                        HttpSession session){
        User user = (User)session.getAttribute(("loginUser"));
        if(user != null && user.getSign().getUsername().equals(username)){
            session.setAttribute("loginUser",null);
            return CommonResponse.createForSuccessMessage("用户注销成功");
        }else{
            return CommonResponse.createForError("用户注销失败，用户名错误");
        }
    }*/

    //购物车部分

    //获取用户购物车列表
    @GetMapping("/carts")
    public CommonResponse<CartVo> getCarts(){
        String username = ThreadLocalUtil.getUsername();
        return cartService.findAllCarts(username);
    }

    //更新购物车数据
    @PutMapping("/carts/{id}")
    public CommonResponse<CartVo> updateCart(@PathVariable("id") String itemId,@RequestParam int quantity){
        String username = ThreadLocalUtil.getUsername();
        cartService.updateCart(itemId,username,quantity);
        recordService.recordAddToCart(username,itemId,quantity);
        CartVo cartVo = cartService.findAllCarts(username).getData();
        for(Cart cart : cartVo.getCarts()){
            if(cart.getItem().getItemId().equals(itemId)){
                cartVo.setLineItemPrice(cart.getItemPrice());
            }
        }
        cartVo.setCarts(null);
        return CommonResponse.createForSuccess(cartVo);
    }

    //新增购物车列表 ————新（可以设置商品的数量）
    @PostMapping("/carts")
    public CommonResponse<CartVo> addCartPlus(@RequestParam String itemId,@RequestParam int quantity){
        String username = ThreadLocalUtil.getUsername();
        CartVo cartVo = cartService.findAllCarts(username).getData();
        //增加的商品在购物车中已经存在
        for(Cart cart : cartVo.getCarts()){
            if(cart.getItem().getItemId().equals(itemId)){
                //int quantity = cart.getCartList().getQuantity()+1;
                cartService.updateCart(itemId,username,quantity);
                //这里又重新查了一遍计算了一遍数据库，有改进空间
                return cartService.findAllCarts(username);
            }
        }
        //如果不存在,则新增一项
        return  cartService.addCart(itemId,username,quantity);
    }

    /*//新增购物车列表 ————旧（默认商品数量为1）
    @PostMapping("/carts")
    public CommonResponse<CartVo> addCart(@RequestParam String itemId){
        String username = ThreadLocalUtil.getUsername();
        CartVo cartVo = cartService.findAllCarts(username).getData();
        //增加的商品在购物车中已经存在
        for(Cart cart : cartVo.getCarts()){
            if(cart.getItem().getItemId().equals(itemId)){
                int quantity = cart.getCartList().getQuantity()+1;
                cartService.updateCart(itemId,username,quantity);
                //这里又重新查了一遍计算了一遍数据库，有改进空间
                return cartService.findAllCarts(username);
            }
        }
        //如果不存在,则新增一项
        return  cartService.addCart(itemId,username);
    }*/

    @DeleteMapping("/carts/{id}")
    public CommonResponse<BigDecimal> deleteCart(@PathVariable("id") String itemId){
        String username = ThreadLocalUtil.getUsername();
        return cartService.deleteCart(username , itemId);
    }

    //orders

    //根据数据库的购物车列表，初始化订单,返回订单编号
    @PutMapping("/order")
    public CommonResponse<Integer> initOrder(){
        String username = ThreadLocalUtil.getUsername();
        try {
            OrderVo orderVo = orderService.initOrder(username);
            if(orderVo.getLineItemVos() == null || orderVo.getLineItemVos().isEmpty()){
                return CommonResponse.createForError("用户购物车为空");
            }
            orderService.insertOrder(orderVo);
            return CommonResponse.createForSuccess(orderVo.getOrders().getOrderId());
        }catch (Exception e){
            return CommonResponse.createForError(e.getMessage());
        }
    }

    //更新用户输入的信息
    @PostMapping("/order/{id}")
    public CommonResponse<OrderVo> updateOrder(@PathVariable("id") int orderId,@RequestBody Orders orders){
        orders.setOrderId(orderId);
        String username = ThreadLocalUtil.getUsername();
        //记录确认订单
        recordService.recordConfirmOrder(username,orderId);
        return orderService.updateOrder(orders);
    }

    //根据订单编号获取订单信息
    @GetMapping("/order/{id}")
    public CommonResponse<OrderVo> getOrderById(@PathVariable("id") int orderId){
        String username = ThreadLocalUtil.getUsername();
        //记录确认订单
        recordService.recordConfirmOrder(username,orderId);
        //清空购物车
        cartService.emptyCart(username);
        return orderService.getOrderVo(orderId);
    }

    //获取用户的全部订单
    @GetMapping("/order")
    public CommonResponse<List<OrderDTO>> getOrderList(){
        String username = ThreadLocalUtil.getUsername();
        return orderService.getAllOrderId(username);
    }


    //Record

    @GetMapping("/records")
    public CommonResponse<RecordVo> getAllRecords(){
        String username = ThreadLocalUtil.getUsername();
        return recordService.getAllRecords(username);
    }

    //Inventory
    @GetMapping("/inventory/{id}")
    public CommonResponse<Inventory> getInventory(@PathVariable("id") String itemId){
        return inventoryService.getInventoryByItemId(itemId);
    }

    //根据id获取description的文字和图片名
    @GetMapping("/desc/{id}")
    public CommonResponse<DescVo> getDescByItemId(@PathVariable("id") String itemId){
        return catalogService.getDescByItemId(itemId);
    }
}
